#include <dirent.h>
#include <cstdio>
#include <errno.h>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <unistd.h>
#include "constants.hpp"
#include "database.hpp"

unsigned int get_current_job() {
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir("in")) == NULL) {
        fprintf(stderr,"Error: (%d) while opening 'in' directory.\n",errno);
        exit(1);
    }
	unsigned int res=UINT_MAX;
    while ((dirp = readdir(dp)) != NULL) {
		if (dirp->d_type!=DT_REG) continue;
        int cur=atoi(dirp->d_name);
        if (res>cur) res=cur;
    }
    if (res==UINT_MAX) 
		res=0;
    closedir(dp);
    return res;	
}

void do_job(database& db, unsigned int current_job) {
	char inname[16],tmpname[16],outname[16];
	sprintf(inname,"in/%d",current_job);
	sprintf(tmpname,"out/t%d",current_job);
	sprintf(outname,"out/%d",current_job);
	FILE *in;
	printf("Waiting for the task %d\n",current_job);
	while ((in=fopen(inname,"r"))==NULL) {
		sleep(1);
	}
	printf("Job %d is found\n",current_job);
	char task[MAXQUERY];
	fgets(task,MAXQUERY,in);
	fclose(in);
	const char *response=db.manage_query(task);
	printf("Answer:\n%s\n",response);
	FILE *out;
	if ((out=fopen(tmpname,"w"))==NULL) {
        fprintf(stderr,"Error: (%d) while writing result.\n",errno);
        exit(1);
	}
	fputs(response,out);
	fclose(out);
	remove(inname);
	rename(tmpname,outname);
}

int main () {
	printf("Starting...\n");
	database db;
	db.manage_query("load db.txt conf.txt");
	printf("Loading successful\n");
	unsigned int current_job=get_current_job();
	printf("Current job is: %d\n",current_job);
	try{
		while (1) {
			do_job(db,current_job);
			current_job++;
			if (current_job%BACKUP_PERIOD==0) {
				db.manage_query("save db.txt");
			}
		}
	} catch(...) {
		db.manage_query("save db.txt");
	}
}
